#include <stdio.h>
#include <stdlib.h>
#include "linklistfun.h"

link_node * creathead(void)
{
	link_node *H = (link_node *)malloc(sizeof(link_node));
	H->data=0;
	H->next=NULL;
	return H;
}

int headinsert(link_node *H)
{
	int num;
	link_node *D = (link_node *)malloc(sizeof(link_node));
	printf(">>>plz input data\n");
	printf(">>");
	scanf("%d",&num);
	D->data=num;
	D->next=H->next;
	H->next=D;
	H->data++;

	return 0;
}

int tailinsert(link_node *H)
{
	int num;
	link_node *p=H;
	link_node *D = (link_node *)malloc(sizeof(link_node));
	printf(">>>plz input data\n");
	printf(">>");
	scanf("%d",&num);
	
	while(p->next!=NULL)
	{
		p=p->next;
	}
	D->data=num;
	D->next=p->next;
	p->next=D;
	H->data++;

	return 0;
}

int headdelete(link_node *H)
{
	if(H->next==NULL)
	{
		return -1;
	}
	link_node *D=H->next;
	H->next=D->next;
	free(D);

	H->data--;
	return 0;
}

int taildelete(link_node *H)
{
	if(H->next==NULL)
	{
		return -1;
	}
	link_node *p=H;
	while(p->next->next!=NULL)
	{
		p=p->next;
	}
	link_node *D=p->next;
	p->next=NULL;
	free(D);

	H->data--;
	return 0;
}

int view(link_node *H)
{
	int pos=0;
	while(H->next!=NULL)
	{
		H=H->next;
		pos++;
		printf(">> <%d> :%d\n",pos,H->data);
	}
	if(pos==0)
	{
		printf("no data!\n");
	}
}

int returnlist(link_node *H)
{
	if(H->next==NULL)
	{
		return -1;
	}

	link_node *D=H->next;
	link_node *p=D->next;
	while(D->next!=NULL)
	{
		p=D->next;
		D->next=p->next;
		p->next=H->next;
		H->next=p;
	}
	return 0;
}

int posinsert(link_node *H)
{
	int inputpos;
	int num;
	link_node *p=H;
	printf(">>>plz input pos <=%d \n",H->data);
	printf(">>> ");
	scanf("%d",&inputpos);
	if(inputpos<0||inputpos>H->data)
	{
		return -1;
	}
	int i;
	for(i=0;i<inputpos;i++)
	{
		p=p->next;
	}

	link_node *D = (link_node *)malloc(sizeof(link_node));
	printf(">>>plz input data\n");
	printf(">>");
	scanf("%d",&num);
	D->data=num;
	D->next=p->next;
	p->next=D;

	H->data++;
	return 0;
}

int posdelete(link_node *H)
{
	link_node *p=H;
	int delepos;
	printf(">>>plz input pos <=%d \n",H->data);
	printf(">>> ");
	scanf("%d",&delepos);
	if(delepos<0||delepos>H->data)
	{
		return -1;
	}
	int i=1;
	for(i=1;i<delepos;i++)
	{
		p=p->next;
	}
	link_node *D=p->next;
	p->next=D->next;
	free(D);
	H->data--;

	return 0;
}


